// 错误处理工具函数

// 自定义错误类
class ApiError extends Error {
  constructor(statusCode, message, isOperational = true, stack = '') {
    super(message);
    this.statusCode = statusCode;
    this.isOperational = isOperational; // 是否为可预期的业务错误
    if (stack) {
      this.stack = stack;
    } else {
      Error.captureStackTrace(this, this.constructor);
    }
  }
}

// 错误响应格式化
const errorResponse = (statusCode, message) => ({
  errCode: statusCode,
  errMsg: message
});

// 成功响应格式化
const successResponse = (data = null, list = null, page = null) => {
  const response = {
    errCode: 0,
    errMsg: 'success'
  };

  if (data !== null) {
    response.data = data;
  }

  if (list !== null) {
    response.list = list;
    if (page !== null) {
      response.page = page;
    }
  }

  return response;
};

// 验证中间件
const validate = (schema) => (req, res, next) => {
  try {
    const validation = schema.validate(req.body);
    if (validation.error) {
      return res.status(400).json({
        errCode: 400,
        errMsg: validation.error.details[0].message
      });
    }
    next();
  } catch (error) {
    next(error);
  }
};

module.exports = {
  ApiError,
  errorResponse,
  successResponse,
  validate
};